<template>
    <div class="custom-tree-container">
        <div class="tree-top-operation" :inline="true">
            <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="appendTop">添加顶级节点</el-button>
            <el-input
                placeholder="输入搜索内容"
                v-model="filterText" class="inputSuffix">
                <el-button slot="append" icon="el-icon-search" @click="searchData"></el-button>
            </el-input>
        </div>
        <!-- 树菜单 -->
        <div class="block" ref="tree" style="margin-top: 20px;overflow-y: auto;">
            <el-tree  :data="dataTreeList"  node-key="id" :props="defaultProps" :expand-on-click-node="false" accordion :load="loadNode" lazy>
                 <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span @click="openDialog(data)" :class="data.hasSame == '1' ? 'tree-name-color' : ''" style="font-size: 15px;font-weight: bold;">{{ node.label }}</span>
                    <span>
                      <el-button circle icon="el-icon-plus" size="mini" type="success" @click="insert(node,data)"></el-button>
                      <el-button circle icon="el-icon-edit" size="mini" type="primary" @click="update(node, data)"></el-button>
                      <el-button circle icon="el-icon-delete" size="mini" type="warning" @click="remove(node, data)"></el-button>
                    </span>
                  </span>
            </el-tree>
        </div>

        <!-- 详情框 -->
        <el-dialog :title="dialogTitle" :visible.sync="isDialog" :close-on-click-modal="false" width="700px">
            <el-form label-position="right" label-width="120px" :model="dialogData">
                <el-form-item label="父级ID" v-if="dialogTitle==='添加顶级节点'">
                    <el-input v-model="dialogData.parentId" disabled></el-input>
                </el-form-item>
                <el-form-item label="父级菜单名称" v-else>
                    <el-autocomplete  class="autocomplete-row"  v-model="dialogData.parentName" :fetch-suggestions="querySearchAsync" placeholder="请输入父级菜单名称" @select="handleSelect" @change="changeHandle"></el-autocomplete>
                </el-form-item>
                <el-form-item label="图纸名称"><el-input v-model="dialogData.drawingName"></el-input></el-form-item>
                <el-form-item v-if="dialogTitle==='添加顶级节点'" label="机器名称"><el-input v-model="dialogData.drawingRemark"></el-input></el-form-item>
                <el-form-item label="图纸编号"><el-input v-model="dialogData.drawingCode"></el-input></el-form-item>
                <el-form-item label="排序"><el-input v-model="dialogData.rank"></el-input></el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitDialog">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 勾选相同节点 -->
        <el-dialog title="编辑关联节点" width="900px" top="50px" :visible.sync="isSameDialog" :close-on-click-modal="false">
             <el-input
                placeholder="输入搜索内容"
                v-model="searchKeywords" class="inputSuffix">
                <el-button slot="append" icon="el-icon-search" @click="searchData"></el-button>
            </el-input>
            <el-tree :data="dataList" ref="sameTree" show-checkbox
            :expand-on-click-node="false"
			      :check-strictly="true" node-key="id"
                     :style="dialogSameTreeHeight"
                     :props="defaultSameProps"
                      :load="loadNode1" lazy>
                <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span style="font-size: 15px;font-weight: bold;">{{ node.label }}</span>
                </span>
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitSameDialog">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import qualitySystem from '@/axios/qualitySystem.js'
    export default {
        data() {
            return {
                tokenId: sessionStorage.getItem("tokenId"),
                defaultProps: {
                    children: 'children',
                    label: 'drawingName',
                    id: 'id'
                },
                filterText:'',
                searchKeywords:'',
                dataList: [],
                dataTreeList:[],
                drawingList:[],
                //详情
                isDialog: false,
                dialogTitle: '',
                dialogData: {
                    id: '',
                    parentId: '',
                    drawingName:'',
                    parentName:'',
                    drawingCode:'',
                    addFlag: '',
                    annexes: '',
                    approvalRemark: '',
                    changeTimes: '',
                    children: '',
                    createTime: '',
                    drawingCreater: '',
                    drawingCreater_name: '',
                    drawingIsPublish: '',
                    drawingNeedTrain: '',
                    drawingPath: '',
                    drawingPrice: '',
                    drawingPublishTime: null,
                    drawingPublisher: '',
                    drawingPublisher_name: '',
                    drawingRemark: '',
                    drawingType: '',
                    drawingType_desc: '',
                    drawingVersion: '',
                    hasSame: '',
                    lastEditTime: '',
                    relevantDept: '',
                    technicsRemark: '',
                    isUpdate: '',
                    updateTime:'',
                    rank:''
                },
                //勾选相同节点
                isSameDialog: false,
                // openSameTreeNode:[],
                dialogSameTreeHeight: {
                    height: (document.documentElement.clientHeight - 210) + 'px',
                    overflowY: 'auto'
                },
                defaultSameProps: {
                    children: 'children',
                    label: 'drawingName',
                    id: 'id'
                },
                drawingDefaultId:'',
            };
        },
        created() {
        },
        mounted(){
            this.$refs.tree.style.height = (document.documentElement.clientHeight - 160) + 'px';
        },
        methods: {
            getData(){/**根据ID获取子节点 */
                let self = this;
                if(self.filterText!==''){
                    qualitySystem.searchDreawingList(self.filterText).then(res=>{
                        self.dataTreeList= res.content;
                        if(self.searchKeywords===''){
                            qualitySystem.getNodeList(0).then(result=>{
                                self.dataList = result.content;
                            })
                        }else{
                            qualitySystem.searchDreawingList(self.searchKeywords).then(result=>{
                                self.dataList = result.content;
                            })
                        }

                    })
                }else{
                    qualitySystem.getNodeList(0).then(res=>{
                        self.dataTreeList= res.content;
                        if(self.searchKeywords===''){
                                qualitySystem.getNodeList(0).then(result=>{
                                    self.dataList = result.content;
                                })

                            }else{
                                qualitySystem.searchDreawingList(self.searchKeywords).then(result=>{
                                    self.dataList = result.content;
                                })
                            }
                    })
                }
            },
            searchData(){/**点击搜索 */
                this.getData();

            },
            loadNode(node, resolve){/**点击树加载子节点 */
                let self = this;
               if(node.level===0){
                    qualitySystem.getNodeList(0).then(res=>{
                        resolve(res.content);
                    })
                }else{
                    qualitySystem.getNodeList(node.data.id).then(res=>{
                        resolve(res.content);
                    })
                }
            },
            loadNode1(node, resolve){/**点击树加载子节点 */
                let self = this;
                if(node.level===0){
                    qualitySystem.getNodeList(0).then(res=>{
                        resolve(res.content);
                    })
                }else{
                    qualitySystem.getNodeList(node.data.id).then(res=>{
                        resolve(res.content);
                    })
                }
            },
            // 顶级节点
            appendTop() {
                this.isDialog = true;
                this.dialogTitle = '添加顶级节点';
                this.dialogData = {
                    id: '',
                    parentId: 0,
                    parentName:'',
                    drawingName:'',
                    drawingCode:'',
                    addFlag: '',
                    annexes: null,
                    approvalRemark: '',
                    changeTimes: '',
                    children: null,
                    createTime: '',
                    drawingCreater: '',
                    drawingCreater_name: '',
                    drawingIsPublish: '',
                    drawingNeedTrain: '',
                    drawingPath: '',
                    drawingPrice: '',
                    drawingPublishTime:null,
                    drawingPublisher: '',
                    drawingPublisher_name: '',
                    drawingRemark: '',
                    drawingType: '',
                    drawingType_desc: '',
                    drawingVersion: '',
                    hasSame: '',
                    lastEditTime: '',
                    relevantDept: '',
                    technicsRemark: '',
                    isUpdate: '',
                    updateTime:'',
                    rank:''
                };
            },
            insert(node, data) {
                this.isDialog = true;
                this.dialogTitle = '添加';
                this.getDrawingList(data.drawingType);
                this.dialogData = {
                    id: '',
                    parentId: data.id,
                    parentName:'',
                    drawingName:'',
                    drawingCode:'',
                    addFlag: '',
                    annexes: null,
                    approvalRemark: '',
                    changeTimes: '',
                    children: null,
                    createTime:null,
                    drawingCreater: '',
                    drawingCreater_name: '',
                    drawingIsPublish: '',
                    drawingNeedTrain: '',
                    drawingPath: '',
                    drawingPrice: '',
                    drawingPublishTime: null,
                    drawingPublisher: '',
                    drawingPublisher_name: '',
                    drawingRemark: '',
                    drawingType: '',
                    drawingType_desc: '',
                    drawingVersion: '',
                    hasSame: '',
                    lastEditTime: null,
                    relevantDept: '',
                    technicsRemark: '',
                    isUpdate: '',
                    updateTime:null,
                    rank:''
                };
            },
            update(node, data) {
                let self = this;
                if(data.parentId==0){
                    self.isDialog = true;
                    self.dialogTitle = '编辑';
                    self.dialogData = data;
                    self.dialogData.parentName = '';
                    self.dialogData.createTime = self.timestampToTime(data.createTime);
                    self.dialogData.children = null;
                }else{
                    qualitySystem.getDreawing(data.parentId).then(res=>{
                        self.isDialog = true;
                        self.dialogTitle = '编辑';
                        self.dialogData ={
                            id: data.id,
                            parentId: data.parentId,
                            parentName:res.content.drawingName,
                            drawingName:data.drawingName,
                            drawingCode:data.drawingCode,
                            addFlag: data.addFlag,
                            annexes: data.annexes,
                            approvalRemark: data.approvalRemark,
                            changeTimes: data.changeTimes,
                            children: data.children,
                            createTime:self.timestampToTime(data.createTime),
                            drawingCreater: data.drawingCreater,
                            drawingCreater_name: data.drawingCreater_name,
                            drawingIsPublish: data.drawingIsPublish,
                            drawingNeedTrain: data.drawingNeedTrain,
                            drawingPath:data.drawingPath,
                            drawingPrice:data.drawingPrice,
                            drawingPublishTime: null,
                            drawingPublisher: data.drawingPublisher,
                            drawingPublisher_name: data.drawingPublisher_name,
                            drawingRemark:data.drawingRemark,
                            drawingType: data.drawingType,
                            drawingType_desc: data.drawingType_desc,
                            drawingVersion: data.drawingVersion,
                            hasSame: data.hasSame,
                            lastEditTime:null,
                            relevantDept: data.relevantDept,
                            technicsRemark: data.technicsRemark,
                            isUpdate: data.isUpdate,
                            updateTime: null,
                            rank:data.rank
                        };
                    })
                }


                self.getDrawingList(data.drawingType);
            },
            remove(node, data) {
                let _this = this;
                this.$confirm('确认删除吗?', '提示', {confirmButtonClass: 'el-button--warning'}).then(() => {
                    _this.$http({
                        url: '/api/adscm/zltx/jyDrawingListTree/delete/'+data.id+'?tokenId=' + _this.tokenId,
                        method: 'post',
                        headers: {'X-Requested-With': 'XMLHttpRequest'},
                    }).then(function (res) {
                        if (res.data.statusCode == 200) {
                            _this.getData();
                        } else {
                            _this.$message.error(res.data.desc);
                        }
                    }).catch(function (catchres) {
                        _this.$message.error("修改失败！请重新修改...");
                    })
                }).catch(() => {});
            },
            submitDialog() {
                 let self = this;
                let type = self.dialogTitle.indexOf('添加')>-1?'insert':'update';
                qualitySystem.addUpdateDreawing(type,self.dialogData).then(res=>{
                    self.isDialog = false;
                    self.getData();
                    self.$message.success(`${self.dialogTitle}成功`)
                },error=>{
                    self.isDialog = false;
                })
            },

            openDialog(data){
                let _this = this;
                _this.isSameDialog = true;
                // _this.showSameTree = true;
                _this.drawingDefaultId = data.id;
                // _this.openSameTreeNode = [];

                this.$http({
                    url: '/api/adscm/zltx/jyDrawingList/selectRelationDraw/'+data.id+'?tokenId=' + _this.tokenId,
                    method: 'post',
                    headers: {'X-Requested-With': 'XMLHttpRequest'},
                }).then(function (res) {
                    if (res.data.statusCode == 200) {
                        let content = res.data.content;
                        let data = [];
                        for(let i = 0;i<content.length;i++){
                            data.push(content[i].id);
                        }
                        _this.$refs.sameTree.setCheckedKeys(data);
                        // _this.openSameTreeNode = data;
                    } else {_this.$message.error(res.data.desc);}
                }).catch(function (catchres) {_this.$message.error("加载失败！请重新加载...");})



            },
            submitSameDialog(){
                let _this = this,paramData=[];
                let rolesTree = this.$refs.sameTree;
                let checkedData=rolesTree.getCheckedNodes();


                for(let i = 0;i<checkedData.length;i++ ){
                    paramData.push({
                        id:'',
                        drawingId:_this.drawingDefaultId,
                        relationId:checkedData[i].id
                    })
                }
                let params = new URLSearchParams();
                params.append("jyDrawingRelations", JSON.stringify(paramData));

                this.$http({
                    url: '/api/adscm/zltx/jyDrawingRelation/insert?tokenId=' + _this.tokenId,
                    method: 'post',
                    headers: {'X-Requested-With': 'XMLHttpRequest'},
                    data: params
                }).then(function (res) {
                    console.log( res.data )
                    if (res.data.statusCode == 200) {
                        _this.isSameDialog = false;
                        _this.getData();
                    } else {
                        _this.$message.error(res.data.desc);
                    }
                }).catch(function (catchres) {
                    _this.$message.error("加载失败！请重新加载...");
                })
            },
            getDrawingList(id){
                let self = this;
                qualitySystem.getAllDreawingList(id).then(res=>{
                  res.content.forEach(element => {
                      element.value =element.drawingName
                  });
                  self.drawingList= res.content;
                })
            },
            querySearchAsync(queryString, callback){
                 let self = this;
                // var restaurants = self.drawingList;
                // var results = queryString ? restaurants.filter(self.createStateFilter(queryString)) : restaurants;
                // cb(results);
                let results = queryString ?  self.drawingList.filter(self.createStateFilter(queryString)) : self.drawingList;
                callback(results);
            },
            createStateFilter(queryString) {
                return (state) => {
                    return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) !==-1);
                };
            },
            changeHandle(val){
            },
            handleSelect(item) {
                this.dialogData.parentId = item.id;
            },
            timestampToTime(timestamp) {
                if (timestamp) {
                    let date = new Date(timestamp);
                    let Y = date.getFullYear() + '-';
                    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
                    let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + " ";
                    let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ":";
                    let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ":";
                    let s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
                    return Y + M + D + h + m + s;
                } else {
                    return '';
                }



            },
        }
    };

</script>
<style scoped>
    @import "equipment.css";
</style>



